@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: 定义颜色
set "GREEN=[92m"
set "YELLOW=[93m"
set "RED=[91m"
set "NC=[0m"

:: 定义项目根目录
pushd %~dp0
cd ..\..\
set "PROJECT_ROOT=%cd%"

echo %YELLOW%=== 开始构建 WVP-GB28181-Pro 项目 ===%NC%

:: 检查Maven是否已安装
where mvn >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo %RED%错误: 未找到Maven。请先安装Maven再运行此脚本。%NC%
    exit /b 1
)

:: 显示Maven版本
echo %YELLOW%Maven版本:%NC%
mvn -v

:: 清理之前的构建
echo %YELLOW%清理之前的构建...%NC%
call mvn clean

:: 跳过测试构建
echo %YELLOW%开始编译打包...%NC%
call mvn package -Dmaven.test.skip=true

:: 检查构建结果
if %ERRORLEVEL% equ 0 (
    :: 查找生成的jar包
    for /f "tokens=*" %%i in ('dir /b /s "%PROJECT_ROOT%\target\*.jar" ^| findstr /v "sources\|javadoc"') do (
        set "JAR_FILE=%%i"
        goto :found_jar
    )
    
    :found_jar
    if defined JAR_FILE (
        for %%F in ("!JAR_FILE!") do set "JAR_SIZE=%%~zF"
        set /a "JAR_SIZE_KB=!JAR_SIZE! / 1024"
        set /a "JAR_SIZE_MB=!JAR_SIZE_KB! / 1024"
        
        if !JAR_SIZE_MB! gtr 0 (
            set "SIZE_DISPLAY=!JAR_SIZE_MB!MB"
        ) else (
            set "SIZE_DISPLAY=!JAR_SIZE_KB!KB"
        )
        
        echo %GREEN%构建成功! JAR文件位置:%NC% !JAR_FILE! (大小: !SIZE_DISPLAY!)
        
        :: 创建一个用于部署的目录
        set "DEPLOY_DIR=%PROJECT_ROOT%\deploy"
        if not exist "!DEPLOY_DIR!" mkdir "!DEPLOY_DIR!"
        
        :: 复制jar文件和配置文件到部署目录
        copy "!JAR_FILE!" "!DEPLOY_DIR!\wvp-gb28181-pro.jar"
        copy "%PROJECT_ROOT%\src\main\resources\application.yml" "!DEPLOY_DIR!\"
        copy "%PROJECT_ROOT%\src\main\resources\logback-spring.xml" "!DEPLOY_DIR!\"
        
        echo %GREEN%部署文件已经准备好:%NC% !DEPLOY_DIR!
        echo %YELLOW%运行方式:%NC% java -jar !DEPLOY_DIR!\wvp-gb28181-pro.jar
    ) else (
        echo %RED%构建似乎成功，但无法找到生成的JAR文件。%NC%
        exit /b 1
    )
) else (
    echo %RED%构建失败，请检查上述错误信息。%NC%
    exit /b 1
)

popd
endlocal 